package com.design.springboot.booksharing.controller.advice;

import com.design.springboot.booksharing.bean.ApiResult;
import com.design.springboot.booksharing.exception.ApiException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;

import java.sql.SQLException;

/**
 * 控制器（@Controller） 的异常统一处理
 *
 * @author admin
 */
@ControllerAdvice
public class ControllerAdviceExceptionHandler extends ResponseEntityExceptionHandler {

    @ExceptionHandler(value = ApiException.class)
    @ResponseBody
    public ApiResult<Object> handlerApiException(ApiException e) {
        ApiResult<Object> apiResult = new ApiResult<>();
        apiResult.setSuccess(false);
        apiResult.setCode(e.getCode());
        apiResult.setMsg(e.getMessage());
        apiResult.setData(null);
        e.printStackTrace();
        return apiResult;
    }

    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public ApiResult<Object> handlerException(Exception e) {
        ApiResult<Object> apiResult = new ApiResult<>();
        apiResult.setSuccess(false);
        //apiResult.setCode(apiResultCodeEnum.getCode());
        apiResult.setMsg(e.getMessage());
        apiResult.setData(null);

        if (HttpRequestMethodNotSupportedException.class.equals(e.getClass())) {
            System.out.println("HttpRequestMethodNotSupportedException");
        } else if (e.getCause() instanceof SQLException) {
            apiResult.setMsg(e.getCause().getMessage());
        }
        e.printStackTrace();
        return apiResult;
    }
}
